<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class RegionController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'Region';

        $this->defaultOrder = [
            ['filed' => 'id', 'order' => 'ASC'],
        ];
    }

    /**
     * Tree
     */
    public function tree(Request $request)
    {
        $param = $request->all();

        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $list = $model->getTreeDatas();

        $data = [
            'data' => $list,
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        //$data = $model->formatDatas($data);
        foreach ($data as &$item) {
            if ($this->sourceUi == self::SOURCE_UI_2) {
                if ($item['level'] < 3) {
                    $item['isLeaf'] = false;
                } else {
                    $item['isLeaf'] = true;
                }
            } else {
                if ($item['level'] < 3) {
                    $item['hasChildren'] = true;
                    $item['children'] = [];
                }
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['parent_code']) && $param['parent_code']) {
            $where[] = ['parent_code', '=', $param['parent_code']];
        } else {
            $where[] = ['level', '=', 0];
        }

        return $where;
    }

    public function save(Request $request)
    {
        DB::beginTransaction();
        try {
            $className = '\\App\\Models\\' . $this->modelName;
            $model = new $className;

            $data = $this->evalData($request);
            if (isset($data['id']) && $data['id']) {
                $info = $model->where('id', $data['id'])->select(['*'])->first();
                if (!$info) {
                    return api_response(self::STATUS_ERROR, '不存在', '');
                }
                $data['updated_at'] = time();
                $message = '保存失败';
                $result = $model->where('id', $data['id'])->update($data);

                $afterAction = '_after_update';
            } else {
                $data['created_at'] = time();
                $message = '创建失败';
                if ($data['parent_code'] == ''){
                    $data['level'] = 0;
                }else{
                    $data['level'] = ($model->where('area_code', $data['parent_code'])->value('level') ?? -1) + 1;
                }
                $result = $model->create($data);
                $data['id'] = $result->id ?? 0;

                $afterAction = '_after_insert';
            }
            if ($result === false) {
                return api_response(self::STATUS_ERROR, $message, []);
            }

            // Query执行后的操作
            $model->$afterAction($data);

            if (isset($info)) {
                $afterRes = $this->afterUpdate($data, $info);
            } else {
                $afterRes = $this->afterInsert($data);
            }
            if ($afterRes['code'] != 1) {
                return api_response(self::STATUS_ERROR, $afterRes['msg'] ?? 'after error', []);
            }

            DB::commit();
            return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
        } catch (Exception $e) {
            DB::rollBack();
            return api_response(self::STATUS_ERROR, '失败', $e->getMessage());
        }
    }


    protected function afterInsert($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterInsert($data);
    }

    protected function afterUpdate($data, $info = [])
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterUpdate($data);
    }

    protected function afterDelete($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $model->getTreeDatas(true);

        return parent::afterDelete($data);
    }
}
